package com.wanshi.exception;


import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Created by IntelliJ IDEA.
 * @Author jzy
 * @Date 2021/11/24 15:00
 */
public class MyExceptionResolver  implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, Exception e) {
        System.out.println("-------------------------------发生异常");

        String message = e.getMessage();

        if(StringUtils.isEmpty(message)){
            message = "未知错误,请联系管理员!";
        }




        ModelAndView mv= new ModelAndView();
        if(!StringUtils.isEmpty( request.getHeader("x-requested-with"))
                && request.getHeader("x-requested-with").equals("XMLHttpRequest")){
            //ajax请求
            FastJsonJsonView view = new FastJsonJsonView();
            Map<String,Object> map = new HashMap<>();
            map.put("code",500);
            map.put("message",message);

            view.setAttributesMap(map);
            mv.setView(view);
        }else{
            //普通请求
            mv.addObject("error",message);
            mv.setViewName("error/error");
        }
        return mv;
    }
}
